package photorganizer.common.transaction;

import photorganizer.common.exception.TechnicalException;

public abstract class TransactionManagerAbstract implements TransactionManager {

	private boolean active;

	/* (non-Javadoc)
	 * @see photorganizer.common.transaction.TransactionManager#isActive()
	 */
	public boolean isActive() {
		return active;
	}

	/* (non-Javadoc)
	 * @see photorganizer.common.transaction.TransactionManager#begin()
	 */
	public void begin() {
		if (active) {
			throw new IllegalStateException(
					"The current thread is already associated with a transaction and this implementation does not support nested transactions");
		}
		active = true;
	}

	/* (non-Javadoc)
	 * @see photorganizer.common.transaction.TransactionManager#commit()
	 */
	public void commit() {
		if (!active) {
			throw new IllegalStateException("The current thread is not associated with a transaction");
		}

		try {
			doCommit();
		}
		catch (Exception e) {
			throw new TechnicalException(e);
		}
		finally {
			active = false;
		}
	}

	/* (non-Javadoc)
	 * @see photorganizer.common.transaction.TransactionManager#rollback()
	 */
	public void rollback() {
		if (!active) {
			throw new IllegalStateException("The current thread is not associated with a transaction");
		}

		try {
			doRollback();
		}
		catch (Exception e) {
			throw new TechnicalException(e);
		}
		finally {
			active = false;
		}
	}

	protected abstract void doCommit() throws Exception;

	protected abstract void doRollback() throws Exception;

}
